package com.mashibing.juc.c_008.interview;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @ClassName T08_Semaphore
 * @Description 案例8，使用semaphore
 * @Author xiongwei.wu
 * @Date 2021/7/13 11:26
 **/
public class T08_Semaphore {
    volatile List<Object> lists = new LinkedList();

    private void add(Object object) {
        lists.add(object);
    }

    private int size() {
        return lists.size();
    }

    static Thread t1, t2;

    public static void main(String[] args) {
        T08_Semaphore t = new T08_Semaphore();

        Semaphore s = new Semaphore(1);

        t1 = new Thread(() -> {
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            for (int i = 0; i < 5; i++) {
                t.add(new Object());
                System.out.println("add: " + i);
            }
            s.release();


            try {
                t2.start();
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                s.acquire();
                for (int i = 5; i < 10; i++) {
                    t.add(new Object());
                    System.out.println(i);
                }
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1");

        t2 = new Thread(() -> {
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            s.release();
        }, "T2");

//        t2.start();
        t1.start();
    }
}
